package com.vito.oa.act.action;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.dubbo.config.annotation.Reference;
import com.esotericsoftware.minlog.Log;
import com.vito.base.authoriza.cache.SessionMap;
import com.vito.base.authoriza.model.DeptModel;
import com.vito.base.authoriza.model.UserModel;
import com.vito.base.authoriza.service.DeptService;
import com.vito.base.model.DataGrid;
import com.vito.base.model.ExportExcelModel;
import com.vito.base.model.ResMsg;
import com.vito.base.model.Result;
import com.vito.base.util.DateUtils;
import com.vito.base.util.ExportExcelUtil;
import com.vito.base.util.Validata;
import com.vito.oa.act.service.OaActStatisticsService;
import com.vito.oa.act.statistics.OaActStatisticsModel;
import com.vito.oa.act.statistics.ProcStatsEnum;

@Controller
@RequestMapping("oa/act/statistics")
public class OaActStatisticsAction {
	@Reference
	private OaActStatisticsService oaActStatisticsService; 
	@Reference
	private DeptService deptService; 

	/**
	 * 个人统计
	 * @param actStatisticsModel
	 * @return
	 */
	@ResponseBody
	@RequestMapping("personal")
	public Result personalStatistics(String procKey,String xType){
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if(user == null){
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("请先登录");
				return rs;
			}
			if(Validata.isNullOrEmpty(procKey)){
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("请选择流程");
				return rs;
			}
			OaActStatisticsModel model = oaActStatisticsService.queryProcStatistics(user.getUserId(),null,procKey,xType);
//			String jKey = "OA_ACT_STATISTICS_"+SpringApplicationContext.getSessionId();
//			JedisTool.setObject(jKey, model, 60);
			rs.setData(model);
			rs.setCode(Result.CODE_OK);
		} catch (Exception e) {
			Log.debug(e.getMessage());
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("请稍后再试");
		}
		return rs;
	}
	
	/**
	 * 团对统计
	 * @param actStatisticsModel
	 * @return
	 */
	@ResponseBody
	@RequestMapping("team")
	public Result teamStatistics(String procKey,String xType,String deptId){
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if(user == null){
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("请先登录");
			}
			if(Validata.isNullOrEmpty(procKey)){
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("请选择流程");
				return rs;
			}
			if(Validata.isNullOrEmpty(deptId)){
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("请选择组织");
				return rs;
			}

			DeptModel dept = new DeptModel();
			dept.setDeptId(deptId);
			dept = deptService.queryDeptById(dept);
			if(dept == null){
				rs.setCode(Result.CODE_PARA_ERROR);
				rs.setMsg("组织无效");
				return rs;
			}
			OaActStatisticsModel model = oaActStatisticsService.queryProcStatistics(null,deptId,procKey,xType);
//			String jKey = "OA_ACT_STATISTICS_"+SpringApplicationContext.getSessionId();
//			JedisTool.setObject(jKey, model, 60);
			rs.setData(model);
			rs.setCode(Result.CODE_OK);
		} catch (Exception e) {
			Log.debug(e.getMessage());
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("请稍后再试");
		}
		return rs;
	}
	
	/**
	 * 获取需要统计的流程
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getStatsProcess")
	public Result getStatsProcess(){
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			if(user == null){
				rs.setCode(Result.CODE_ERROR);
				rs.setMsg("请先登录");
			}
			List<Map<String, String>> proc = new ArrayList<Map<String,String>>();
			Map<String, String> map;
			for(ProcStatsEnum item : ProcStatsEnum.values()){
				map = new HashMap<String,String>();
				map.put("key", item.getKey());
				map.put("name",item.getProcName());
				proc.add(map);
			}
			rs.setData(proc);
			rs.setCode(Result.CODE_OK);
		} catch (Exception e) {
			Log.debug(e.getMessage());
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("请稍后再试");
		}
		return rs;
	}
	
	/**
	 * 获取用户部门级子部门
	 * @return
	 */
	@ResponseBody
	@RequestMapping("queryDeptsOfUsers")
	public Result queryDeptsOfUsers(){
		Result rs = new Result();
		try {
			UserModel user = SessionMap.getObj();
			rs.setCode(Result.CODE_OK);
			rs.setData(oaActStatisticsService.queryDeptsOfUser(user.getDeptCode()));
		} catch (Exception e) {
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("查询异常");
		}
		return rs;
	}
	
	@ResponseBody
	@RequestMapping("exportExcel")
	public Result exportExcel(String procKey,String xType,String deptId,HttpServletResponse response){
		Result rs = new Result();
		UserModel user = SessionMap.getObj();
		OaActStatisticsModel statsModel = null;
		if(Validata.isNullOrEmpty(deptId)){
			statsModel = oaActStatisticsService.queryProcStatistics(user.getUserId(),null,procKey,xType);
		}else{
			statsModel = oaActStatisticsService.queryProcStatistics(null,deptId,procKey,xType);
		}
		if(statsModel != null){
			List<String> xData = statsModel.getxData();
			List<Number> yData = statsModel.getyData();
			
			HSSFWorkbook wb = new HSSFWorkbook();	
			ExportExcelUtil excelUtil = new ExportExcelUtil();
			ExportExcelModel excelModel = new ExportExcelModel();
		   
			excelModel.setCreateTime(DateUtils.formatToStr(new Date(), "yyyy-MM-dd HH:mm"));
			excelModel.setCreator(user.getUserName());
			excelModel.setFontSize(12);
			excelModel.setDefaultRowHeight((short)400);
			//标题
		    HSSFSheet sheet = wb.createSheet(statsModel.getProcName());
		    sheet.setDefaultColumnWidth(40);
		    int index = 0;//行索引
		    
		    int columnSize = 2;
		    excelModel.setFontSize(14);
		    HSSFCellStyle styleTitle =  excelUtil.setExcleTitleStyle(wb, excelModel, true);
		    styleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
		    String title = user.getDeptParentName()+"—"+statsModel.getProcName()+"统计";
		    HSSFRow rowTitle1 = sheet.createRow(index);  
		    rowTitle1.setHeight((short)600);
	        HSSFCell cellTitle = rowTitle1.createCell(0);
	        cellTitle.setCellStyle(styleTitle);
	        cellTitle.setCellValue(title);
	        sheet.addMergedRegion(new CellRangeAddress(0,0,0,columnSize-1));
	        index++;
	        
//	        excelModel.setFontSize(12);
//	        HSSFRow rowtitle2 = sheet.createRow(index);
//	        rowtitle2.setHeight(excelModel.getDefaultRowHeight());
//	        HSSFCellStyle styleTitle2 =  excelUtil.setExcleTitleStyle(wb, excelModel, true);
//	        HSSFCell cellTitle2 = rowtitle2.createCell(0);
//	        styleTitle2.setAlignment(HSSFCellStyle.ALIGN_LEFT);
//	        cellTitle2.setCellStyle(styleTitle2); 
//	        cellTitle2.setCellValue("制表人："+excelModel.getCreator()+"    制表时间："+excelModel.getCreateTime());
//	        sheet.addMergedRegion(new CellRangeAddress(1,1,0,columnSize-1));
//	        index++;
	        
	        //表头
	        HSSFRow rowHeader = sheet.createRow(index);
	        rowHeader.setHeight(excelModel.getDefaultRowHeight());
	        HSSFCellStyle styleHeader = excelUtil.setExcleTitleStyle(wb, excelModel, false);
	        styleHeader.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	        HSSFCell header1 = rowHeader.createCell(0);
	        HSSFCell header2 = rowHeader.createCell(1);
	        header1.setCellStyle(styleHeader);
	        header2.setCellStyle(styleHeader);
	        header1.setCellValue("日期/"+statsModel.getxTypeName());
	        header2.setCellValue(statsModel.getyTypeName());
	        index++;
	        
	        //主题数据
	        int rowNumber = xData.size();
	        HSSFRow row;
	        HSSFCellStyle rowStyle;
	        HSSFCell cell1;
	        HSSFCell cell2;
	        rowStyle = excelUtil.setExcleTitleStyle(wb, excelModel, true);
	        for(int i = 0;i < rowNumber;i++){
	        	rowStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	        	row = sheet.createRow(index);
	        	row.setHeight(excelModel.getDefaultRowHeight());
	        	cell1 = row.createCell(0);
	        	cell1.setCellStyle(rowStyle);
	        	cell1.setCellValue(xData.get(i));
	        	cell2 = row.createCell(1);
	        	cell2.setCellStyle(rowStyle);
	        	cell2.setCellValue(String.valueOf(yData.get(i)));
	        	index++;
	        }
			try {
				response.reset();
				response.setContentType("application/x-download");
				response.setHeader("Content-Disposition","attachment;filename="+ new String((excelModel.getCreateTime()+".xls").getBytes("gb2312"),"ISO8859-1"));
				response.setHeader("Pragma", "No-cache");  
				response.setHeader("Cache-Control", "No-cache");  
				response.setDateHeader("Expires", 0);
				OutputStream out = response.getOutputStream();
				wb.write(out);
			    out.flush();
			    out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			 return null;
		}else{
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg("参数错误");
			return null;
		}
	}
	
	
	/**
	 * 获取指定时间段内完结流程的总消耗<请假的总天数/出差的总天数>
	 * @param processKey
	 * @param startTime
	 * @param endTime
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getProcessStatisticData")
	public Result getProcessStatisticData(String processKey,String startTime,String endTime,String userId){
		Result reslut = new Result();
		reslut.setCode(Result.CODE_OK);
		
		Double time =  oaActStatisticsService.queryStatisticProcessStatisticData(processKey, startTime,endTime,userId);
		reslut.setData(time);
		if(time <= 0){
			reslut.setMsg("暂无数据");
			reslut.setData(0);
		}
		return reslut;
	}
	
	/**
	 * 获取指定时间段内流程的摘要
	 * @param processKey
	 * @param startTime
	 * @param endTime
	 * @param userId
	 * @return
	 */
	@ResponseBody
	@RequestMapping("getProcessAbstractList")
	public Result getProcessAbstractList(String processKey,String startTime,String endTime,String userId){
		Result reslut = new Result();
		reslut.setCode(Result.CODE_OK);
		
		List<Map<String, String>> data =  oaActStatisticsService.getProcessAbstractList(processKey, startTime,endTime,userId);
		DataGrid<Map<String, String>> dg = new DataGrid<Map<String, String>>();
		if(null == data){
			dg.setTotal(0);
			dg.setRows(null);
		}else{
			dg.setTotal(data.size());
			dg.setRows(data);
		}
		reslut.setData(dg);

		return reslut;
	}
	/**
	 * 获取指定时间段内系统流程统计汇总
	 * @param processKey
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	@ResponseBody
	@RequestMapping("queryStatisticAllOfCompany")
	public Result queryStatisticAllOfCompany(String startTime,String endTime){
		Result rs = new Result();
		UserModel user = SessionMap.getObj();
		try{
			List<Map<String, Object>> data =  oaActStatisticsService.queryStatisticAllOfCompany(startTime,endTime,user.getDeptParentId());
			rs.setData(data);
			rs.setCode(Result.CODE_OK);
		}catch(Exception e){
			rs.setCode(Result.CODE_ERROR);
			rs.setMsg(ResMsg.EXECERR);
		}
		return rs;
	}
}
